package com.chuangke.fss.minio;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.chuangke.common.exception.ChuangkeException;
import com.chuangke.file.model.FileBrief;
import com.chuangke.file.model.FileChunk;
import com.chuangke.fss.FSS;
import com.chuangke.fss.model.FSSObject;
import com.chuangke.fss.model.StorageType;

import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;

@Component
public class FSSMinIO implements FSS {

	@Autowired
	private MinioClient minioClient;
	@Autowired
	private MinioProperties minioProperties;

	@Override
	public FSSObject upload(FSSObject fssObject) {
		fssObject.setStorageType(StorageType.minio.name());
		try {
			minioClient.putObject(
					PutObjectArgs.builder().bucket(minioProperties.getBucketName()).object(fssObject.getStorage2())
							.stream(new ByteArrayInputStream(fssObject.getObjectContent()), fssObject.getSize(), -1)
							.contentType(fssObject.getMimeType()).build());
			fssObject.setStorage1(minioProperties.getBucketName());
			fssObject.setStorage2(fssObject.getStorage2());
		} catch (Exception e) {
			throw new ChuangkeException(e);
		}
		return fssObject;
	}

	@Override
	public FileBrief uploadAppenderFile(FileBrief fileBrief) {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean appenderFile(FileChunk fileChunk) {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean mergeFile(FileBrief fileBrief) {
		throw new UnsupportedOperationException();
	}

	@Override
	public FSSObject download(FSSObject fssObject) {
		try {
			InputStream inputStream = minioClient.getObject(
					GetObjectArgs.builder().bucket(fssObject.getStorage1()).object(fssObject.getStorage2()).build());
			fssObject.setObjectContent(IOUtils.toByteArray(inputStream));
		} catch (Exception e) {
			throw new ChuangkeException(e);
		}
		return fssObject;
	}

	@Override
	public void delete(FSSObject fssObject) {
		try {
			minioClient.removeObject(
					RemoveObjectArgs.builder().bucket(fssObject.getStorage1()).object(fssObject.getStorage2()).build());
		} catch (Exception e) {
			throw new ChuangkeException(e);
		}
	}

}
